<template>
  <a-modal 
    title="提交任务" 
    v-model:visible="visible" 
    :confirm-loading="loading" 
    @ok="handleSubmit" 
    @cancel="handleCancel"
    width="720px"
    class="task-submit-modal"
  >
    <div v-if="loading" class="loading-container">
      <a-spin tip="加载中..." />
    </div>

    <div v-else-if="errorMessage" class="error-container">
      <a-alert :message="errorMessage" type="error" showIcon />
    </div>

    <div v-else-if="nextNodes.length === 0" class="empty-container">
      <a-empty description="没有可用的下一个节点" />
    </div>

    <div v-else class="task-submit-container">
      <!-- 选择节点（如果有多个节点） -->
      <div v-if="nextNodes.length > 1" class="section-wrapper">
        <div class="section-header">
          <h3 class="section-title">节点选择</h3>
          <div class="section-divider"></div>
        </div>
        
        <div class="node-grid-container">
          <div 
            v-for="node in nextNodes" 
            :key="node.Id" 
            class="node-card" 
            :class="{ 'selected': selectedNodeId === node.Id }"
            @click="selectedNodeId = node.Id; onNodeChange()"
          >
            <div class="node-card-inner">
              <div class="node-card-header">
                <span class="node-card-radio">
                  <a-radio :checked="selectedNodeId === node.Id" :value="node.Id" />
                </span>
                <div class="node-name">{{ node.Name }}</div>
              </div>
              <div class="node-card-body">
                <div class="node-assignee" v-if="node.Assignee">
                  <a-tag color="blue">预设办理人: {{ getUserInfoById(node.Assignee) }}</a-tag>
                </div>
                <div class="node-candidates" v-if="node.CandidateUsers && node.CandidateUsers.length > 0">
                  <a-tag color="green">候选用户: {{ getCandidateUsersText(node.CandidateUsers) }}</a-tag>
                </div>
                <div v-if="!node.Assignee && (!node.CandidateUsers || node.CandidateUsers.length === 0)" class="no-users">
                  <a-tag color="orange">需要指定用户</a-tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 当前节点信息（只有一个节点时显示） -->
      <div v-else class="section-wrapper">
        <div class="section-header">
          <h3 class="section-title">当前节点</h3>
          <div class="section-divider"></div>
        </div>
        
        <div class="single-node-card">
          <div class="node-name">{{ nextNodes[0].Name }}</div>
          <div class="node-details">
            <div v-if="nextNodes[0].Assignee" class="node-assignee-tag">
              <a-tag color="blue">预设办理人: {{ getUserInfoById(nextNodes[0].Assignee) }}</a-tag>
            </div>
            <div v-else-if="nextNodes[0].CandidateUsers && nextNodes[0].CandidateUsers.length > 0" class="node-candidates-tags">
              <a-tag color="green">候选用户: {{ getCandidateUsersText(nextNodes[0].CandidateUsers) }}</a-tag>
            </div>
            <div v-else class="no-users">
              <a-tag color="orange">需要指定用户</a-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 选择办理用户（如果没有预设办理人和候选用户，或需要重新指定） -->
      <div v-if="showUserSelection" class="section-wrapper">
        <div class="section-header">
          <h3 class="section-title">用户选择</h3>
          <div class="section-divider"></div>
        </div>
        
        <div class="user-selection-area">
          <a-button 
            type="primary" 
            @click="showSelectUserModal = true" 
            class="select-user-button"
          >
            {{ selectedUserIds.length > 0 ? '已选择 ' + selectedUserIds.length + ' 个用户' : '选择用户' }}
          </a-button>
          
          <!-- 已选用户标签显示 -->
          <div v-if="selectedUserIds.length > 0" class="selected-users-tags">
            <div class="selected-users-label">已选择的用户：</div>
            <div class="tags-container">
              <a-tag 
                v-for="userId in selectedUserIds" 
                :key="userId" 
                :closable="false"
                class="user-tag"
              >
                {{ getUserInfoById(userId) }}
              </a-tag>
            </div>
          </div>
          <div v-if="showUserSelection && selectedUserIds.length === 0" class="user-selection-required">
            <a-alert message="必须选择一个用户" type="warning" show-icon />
          </div>
        </div>
      </div>

      <!-- 审批意见 -->
      <div class="section-wrapper">
        <div class="section-header">
          <h3 class="section-title">审批意见</h3>
          <div class="section-divider"></div>
        </div>
        
        <div class="approval-comment-area">
          <a-textarea 
            v-model:value="approvalComment" 
            class="reason-textarea" 
            placeholder="请输入审批意见（选填）" 
            :rows="3"
            :maxlength="500" 
            showCount 
          />
        </div>
      </div>
    </div>

    <!-- 用户选择模态框 -->
    <SelectUser 
      :visible="showSelectUserModal" 
      :multiple="false" 
      :default-user-ids="selectedUserIds"
      :on-confirm="handleUserConfirm" 
      :on-cancel="handleUserCancel" 
    />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue';
import { message, notification } from 'ant-design-vue';
import { getNextNodeInfo, jumpTask } from '@/api/flowToDo';
import { getUserDataList } from '@/api/syssetting/user';
import SelectUser from '@/components/sys/selectUser.vue';

// 定义组件的Props
interface TaskSubmitModalProps {
  visible: boolean;
  taskId: string;
  taskInfo: object;
  onSuccess?: () => void;
  onCancel?: () => void;
}

// 定义节点的类型
interface NextNode {
  Id: string;
  Name: string;
  Assignee: string | null;
  CandidateUsers: string[];
  [key: string]: any;
}

// 定义用户的类型
interface User {
  id: string;
  name: string;
}

// 接收Props
const props = defineProps<TaskSubmitModalProps>();

// 响应式数据

const visible = ref(false);
const loading = ref(false);
const errorMessage = ref('');
const nextNodes = ref<NextNode[]>([]);
const selectedNodeId = ref('');
const selectedUserIds = ref<string[]>([]);
const showUserSelection = ref(false);
const showSelectUserModal = ref(false);
const approvalComment = ref('');
const allUsers = ref<User[]>([]);

// 监听visible变化
watch(() => props.visible, (newValue) => {
  visible.value = newValue;
  if (newValue) {
    loadNextNodes();
  } else {
    // 关闭时重置状态
    resetState();
  }
});

// 重置状态
const resetState = () => {
  nextNodes.value = [];
  selectedNodeId.value = '';
  selectedUserIds.value = [];
  showUserSelection.value = false;
  showSelectUserModal.value = false;
  approvalComment.value = '';
  errorMessage.value = '';
  loading.value = false;
};

// 加载下一个节点信息
const loadNextNodes = async () => {
  loading.value = true;
  errorMessage.value = '';

  try {
    // 获取下一个节点信息
    const nodeResponse = await getNextNodeInfo({ taskId: props.taskId });

    if (nodeResponse.data.Code === 1 && nodeResponse.data.Data) {
      const nodesData = Array.isArray(nodeResponse.data.Data) ? nodeResponse.data.Data : [nodeResponse.data.Data];
      nextNodes.value = nodesData.map((node: any) => ({
        Id: node.Id || node.id || '',
        Name: node.Name || node.name || '未命名节点',
        Assignee: node.Assignee || null,
        CandidateUsers: Array.isArray(node.CandidateUsers) ? node.CandidateUsers : [],
        ...node
      }));

      // 加载用户信息，用于显示用户名
      await loadUserData();

      // 选中第一个节点
      if (nextNodes.value.length > 0) {
        selectedNodeId.value = nextNodes.value[0].Id;
        checkUserSelectionNeeded();
      }
    } else {
      throw new Error(nodeResponse.data.Message || '获取下一个节点信息失败');
    }
  } catch (error) {
    console.error('加载下一个节点信息失败:', error);
    errorMessage.value = '获取下一个节点信息失败';
    notification.error({
      message: '错误',
      description: '获取下一个节点信息失败',
    });
  } finally {
    loading.value = false;
  }
};

// 加载用户数据
const loadUserData = async () => {
  try {
    const userResponse = await getUserDataList();
    if (userResponse.data?.Data) {
      allUsers.value = userResponse.data.Data.map((user: any) => ({
        id: String(user.Id || user.id || ''),
        name: user.RealName || user.name || '未知用户'
      }));
    }
  } catch (error) {
    console.error('加载用户数据失败:', error);
    // 即使加载用户数据失败，也不影响主流程
  }
};

// 检查是否需要选择用户
const checkUserSelectionNeeded = () => {
  const selectedNode = nextNodes.value.find(node => node.Id === selectedNodeId.value);
  if (selectedNode) {
    // 如果没有预设办理人且没有候选用户，则需要选择用户
    showUserSelection.value = !selectedNode.Assignee && (!selectedNode.CandidateUsers || selectedNode.CandidateUsers.length === 0);
    // 如果需要选择用户，则清空已选用户
    if (showUserSelection.value) {
      selectedUserIds.value = [];
    }
  }
};

// 当节点选择变化时
const onNodeChange = () => {
  checkUserSelectionNeeded();
};

// 处理用户选择确认
const handleUserConfirm = (userIds: string[]) => {
  // 确保只能选择一个用户
  if (userIds.length > 0) {
    selectedUserIds.value = [userIds[0]];
  } else {
    selectedUserIds.value = [];
  }
  showSelectUserModal.value = false;
};

// 处理用户选择取消
const handleUserCancel = () => {
  showSelectUserModal.value = false;
};

// 根据用户ID获取用户信息
const getUserInfoById = (userId: string): string => {
  const user = allUsers.value.find(u => u.id === userId);
  return user ? user.name : `用户(${userId})`;
};

// 获取候选用户文本（限制显示数量，避免过长）
const getCandidateUsersText = (userIds: string[]): string => {
  const displayCount = 3;
  const names = userIds.slice(0, displayCount).map(id => getUserInfoById(id));
  if (userIds.length > displayCount) {
    return `${names.join(', ')} 等${userIds.length}人`;
  }
  return names.join(', ');
};

// 处理提交
const handleSubmit = async () => {
  // 验证选择
  if (showUserSelection.value && selectedUserIds.value.length === 0) {
    message.warning('必须选择一个办理用户');
    return;
  }

  loading.value = true;

  try {
    // 构建提交参数
    const submitParams: any = {
      TaskId: props.taskId,
      Comment: approvalComment.value.trim()
    };

    // 如果选择了节点且有多个节点
    if (nextNodes.value.length > 1 && selectedNodeId.value) {
      submitParams.NextNodeId = selectedNodeId.value;
    }

    // 如果需要选择用户
    if (showUserSelection.value && selectedUserIds.value.length > 0) {
      submitParams.Assignees = selectedUserIds.value;
    }

    // 提交任务
    jumpTask({
      processInstanceId: props.taskInfo.ProcessInstanceId,
      taskId: props.taskInfo.TaskDefinitionKey,
      targetNodeId: selectedNodeId.value,
      assignee: selectedUserIds.value.length > 0 ? selectedUserIds.value[0] : null,
    }).then((res) => {
      console.log(res);
      // 任务提交成功后，可以刷新任务列表或关闭当前模态框
      message.success('任务提交成功');
      visible.value = false;
      
      // 调用成功回调
      if (props.onSuccess) {
        props.onSuccess();
      }
    }).catch((err) => {
      notification.error({
        message: '错误',
        description: '请求失败:' + err,
      });
    });
  } catch (error) {
    console.error('任务提交失败:', error);
    message.error(error.message || '任务提交失败');
  } finally {
    loading.value = false;
  }
};

// 处理取消
const handleCancel = () => {
  visible.value = false;
  if (props.onCancel) {
    props.onCancel();
  }
};
</script>

<style scoped lang="scss">
.task-submit-modal {
  :deep(.ant-modal-content) {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  }
  
  :deep(.ant-modal-header) {
    background: linear-gradient(135deg, #1890ff, #40a9ff);
    padding: 16px 24px;
    border-bottom: none;
    
    .ant-modal-title {
      color: white;
      font-weight: 500;
      font-size: 18px;
    }
  }
  
  :deep(.ant-modal-body) {
    padding: 20px;
  }
  
  :deep(.ant-modal-footer) {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
  }
}

.reason-textarea {
  resize: vertical;
  min-height: 80px;
}

.task-submit-container {
  .section-wrapper {
    margin-bottom: 20px;
    background: #fafafa;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.09);
      transform: translateY(-2px);
    }
    
    .section-header {
      margin-bottom: 16px;
      
      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin: 0;
      }
      
      .section-divider {
        height: 2px;
        background: linear-gradient(90deg, #1890ff, #40a9ff);
        border-radius: 1px;
        margin-top: 8px;
      }
    }
  }
  
  .node-grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 16px;
    margin-top: 16px;
  }
  
  .node-card {
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    background: white;
    
    &:hover {
      border-color: #1890ff;
      box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
      transform: translateY(-2px);
    }
    
    &.selected {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    }
    
    .node-card-inner {
      padding: 16px;
    }
    
    .node-card-header {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      
      .node-card-radio {
        margin-right: 12px;
      }
      
      .node-name {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }
    
    .node-card-body {
      .node-assignee,
      .node-candidates,
      .no-users {
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
  
  .single-node-card {
    padding: 16px;
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    background: white;
    
    .node-name {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 12px;
    }
    
    .node-details {
      .node-assignee-tag,
      .node-candidates-tags,
      .no-users {
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
  
  .user-selection-area {
    .select-user-button {
      width: auto;
      min-width: 120px;
      max-width: 300px;
      height: 40px;
      border-radius: 20px;
      margin-bottom: 16px;
      background: linear-gradient(135deg, #1890ff, #40a9ff);
      border: none;
      box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
      }
    }
    
    .selected-users-tags {
      .selected-users-label {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
      }
      
      .tags-container {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .user-tag {
          margin: 0;
          background: #e6f7ff;
          border-color: #91d5ff;
          border-radius: 16px;
          padding: 4px 12px;
        }
      }
    }
    
    .user-selection-required {
      margin-top: 12px;
    }
  }
  
  .approval-comment-area {
    .reason-textarea {
      border-radius: 8px;
    }
  }
}

// 添加.loading-container的样式，使其居中显示
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}
</style>